package com.yuluke.ylsaudiorecorder.record;

import android.annotation.SuppressLint;
import android.media.AudioRecord;
import android.util.Log;

import com.yuluke.ylsaudiorecorder.FileUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

@SuppressLint("MissingPermission")
public class RecordTask {

    private static final String TAG = "YlsRec_Task";
    private final AudioRecord mAudioRecord;
    private final StateInstance mStateInstance;
    private final RecordConfig.BaseConfig mCfg;
    private String mFilePath;

    public RecordTask(String path) {
        mFilePath = path;
        mCfg = RecordConfig.getInstance().getSimpleConfig();
        mAudioRecord = createAudioRecordBySimpleConstructor();
        mStateInstance = StateInstance.getInstance();
    }

    private AudioRecord createAudioRecordBySimpleConstructor() {
        return new AudioRecord(mCfg.getSource(),
                mCfg.getSampleRate(),
                mCfg.getChannel(),
                mCfg.getFormat(),
                mCfg.getBufferSize());
    }

    public void start() {
        if (mStateInstance.isStarted()) {
            Log.e(TAG, "start return, already stated.");
            return;
        }
        Log.i(TAG, "#### start");
        mAudioRecord.startRecording();
        mStateInstance.change(StateInstance.STATE_RECORD_STARTED);
        byte[] buffer = new byte[mCfg.getBufferSize()];
        File file = new File(getTempFilePath());
        Log.i(TAG, "start, file path:" + file.getAbsolutePath());
        if (file.exists()) {
            boolean delResult = file.delete();
            Log.i(TAG, "start, file(" + file.getAbsolutePath() + ")exist and delete result:" + delResult);
        }
        try {
            boolean newFileResult = file.createNewFile();
            Log.i(TAG, "start, create new file result:" + newFileResult);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        while (mStateInstance.isStarted()) {
            int len = mAudioRecord.read(buffer, 0 , buffer.length);
            if (len > 0) {
                try {
                    //Log.i(TAG, "start, write to file byte size:" + len);
                    fos.write(buffer, 0, buffer.length);
                    fos.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                Log.i(TAG, "start, AudioRecord read error:" + len);
                mStateInstance.change(StateInstance.STATE_RECORD_ERR);
                break;
            }
        }
        if (mStateInstance.isError()) {
            Log.e(TAG, "start, record err.");
        }
        mStateInstance.change(StateInstance.STATE_RECORD_STOPED);
        Log.i(TAG, "start return.");
    }

    private String getTempFilePath() {
        // TODO
        if (!FileUtils.createOrExistsDir(mFilePath)) {
            Log.e(TAG, "文件夹创建失败：" + mFilePath);
        }
        String fileName = String.format(Locale.getDefault(),
                "record_tmp_%s", FileUtils.getNowString(new SimpleDateFormat("yyyyMMdd_HH_mm_ss", Locale.SIMPLIFIED_CHINESE)));
        return String.format(Locale.getDefault(), "%s%s.pcm", mFilePath, fileName);
    }

    public void stop() {
        Log.i(TAG, "#### stop");
        mStateInstance.change(StateInstance.STATE_RECORD_STOPED);
    }
}
